package handler

import (
	"fmt"
	"net/http"
	"strings"

	"gitee.com/wind-mask/url-shortener/shortener"
	"gitee.com/wind-mask/url-shortener/store"
	"github.com/gin-gonic/gin"
)

func CreateShortUrl(c *gin.Context) {
	var creationRequest UrlCreationRequest
	if err := c.ShouldBindJSON(&creationRequest); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	hash_url := creationRequest.LongUrl

	shortUrl := shortener.GenerateShortLink(hash_url, creationRequest.UserId)
	for {
		u, _ := store.RetrieveInitialUrl(shortUrl)
		if u == "" {
			break
		} else {
			shortUrl = shortener.GenerateShortLink(hash_url+" ", creationRequest.UserId)
		}
	}

	store.SaveUrlMapping(shortUrl, hash_url, creationRequest.UserId)

	host := "http://localhost:9808/"
	c.JSON(200, gin.H{
		"message":   "short url created successfully",
		"short_url": host + shortUrl,
	})

}
func HandleShortUrlRedirect(c *gin.Context) {
	shortUrl := c.Param("shortUrl")
	initialUrl, err := store.RetrieveInitialUrl(shortUrl)
	if err != nil {

		if strings.HasPrefix(err.Error(), "短链接不存在") {
			c.JSON(http.StatusNotFound, gin.H{"error": "short URL not found"})
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "internal server error"})
			fmt.Printf("Error retrieving initial URL: %v\n", err)
			return
		}
	}
	c.Redirect(302, initialUrl)
}
